var co = require('co');
var memberDao = require('../../model/member/member');
var controllerBase = require('../../core/controllerBase');
var UUID = require('node-uuid');
var crypto = require('crypto')
const WXBiZDataCrypt = require('../../common/WXBizDataCrypt');
var config = require('../../configuration.json');
var rpc = require('../../core/rpc/rpcUtility');
const cache = require("../../core/cache/memorycache");
var date = require("silly-datetime");
const { request } = require('http');
const { LOADIPHLPAPI } = require('dns');

class LoginController extends controllerBase {
    /*
    * 类构造函数
    * 设置类需要的数据实体操作实例
    */
    constructor(application) {
        ///将对应的数据库实体对象传递至基类
        super(application, new memberDao());
    }
    /*
    * 初始化控制器中的路由
    * 以下由代码生成器默认添加了增删改查的几个路由处理器，开发人员
    * 根据实际情况可以继续添加其他路由，或删除现有路由
    */

    initializeRouter(instance) {
 

        //获取分类
        this.app.get('/api/allCat', function (req, res) {
            co(instance.allCat(req, res))
                .then(result => instance.responseResult(req, res, result))
                .catch(result => instance.responseResult(res, res, result))
        });

        //修改分类
        this.app.get('/api/updateCat/:catelog_id', function (req, res) {
            co(instance.updateCat(req, res))
                .then(result => instance.responseResult(req, res, result))
                .catch(result => instance.responseResult(res, res, result))
        });

        // 获取详情列表
        this.app.get('/api/allArt', function (req, res) {
            co(instance.allArt(req, res))
                .then(result => instance.responseResult(req, res, result))
                .catch(result => instance.responseResult(res, res, result))
        });


        // 获取详情单个
        this.app.get('/api/allArtOne/:article_id', function (req, res) {
            co(instance.allArtOne(req, res))
                .then(result => instance.responseResult(req, res, result))
                .catch(result => instance.responseResult(res, res, result))
        });


        //修改详情
        this.app.get('/api/updateArt/:article_id', function (req, res) {
            co(instance.updateArt(req, res))
                .then(result => instance.responseResult(req, res, result))
                .catch(result => instance.responseResult(res, res, result))
        });


        


        //用户：取消收藏楼盘
        this.app.post('/login/delFavorItem', function (req, res) {
            co(instance.delFavorItem(req, res))
                .then(result => instance.responseResult(req, res, result))
                .catch(result => instance.responseResult(res, res, result))
        });



    }

    * allCat(req, res) {
        let r = {}; 
        let catelog_name = req.query.catelog_name; 
        let catSql = `SELECT * FROM cnt_catelog where  rec_isdeleted = 0   `  ;

        //输出模糊查询  
        if(catelog_name)
        {
            catSql +=` and catelog_name like '%${catelog_name}%' `;
        }

        //输出到前端  
        r.cats = yield this._daoModel.query(catSql);
    
        return {
            code: 200,
            successed: true, 
            cats:r.cats.rows
        }
    }

    * allArt(req, res) {
        let r = {}; 
        let article_title = req.query.article_title; 
        let catelog_id = req.query.catelog_id; 
        let catSql = `SELECT * FROM cnt_article where  rec_isdeleted = 0   `  ;

        
        //输出模糊查询  
        if(catelog_id)
        {
            catSql +=` and catelog_id = ${catelog_id} `;
        }
        if(article_title)
        {
            catSql +=` and article_title like '%${article_title}%' `;
        }

        //输出到前端  
        r.cats = yield this._daoModel.query(catSql);

        return {
            code: 200,
            successed: true, 
            cats:r.cats.rows
        }
    }

    
    * allArtOne(req, res) {
        let r = {}; 
        let article_id = req.params.article_id; 
        let catSql = `SELECT  article_id,catelog_id,article_title as nameit,ext_field3,article_cover,article_brief,hbn,article_share,article_label,rec_isdeleted FROM cnt_article where  article_id = ${article_id} order by id desc  `  ;
        //输出到前端  
        r.cats = yield this._daoModel.query(catSql);

        return {
            code: 200,
            successed: true, 
            cats:r.cats.rows[0]
        }
    }

    * updateCat(req, res) {
        let r = {}; 
        
        let catelog_id = req.params.catelog_id; 
        let cn = req.query.cn; 
        let cv = req.query.cv; 
        let catSql = `update cnt_catelog set ${cn} = '${cv}' where catelog_id='${catelog_id}'    `  ;

        //输出到前端  
        r.cats = yield this._daoModel.query(catSql);

        return {
            code: 200,
            successed: true, 
            cats:r.cats.rows,
            msg:"修改成功"
        }
    }


    * updateArt(req, res) {
        let r = {}; 
        
        let article_id = req.params.article_id; 
        let cn = req.query.cn; 
        let cv = req.query.cv; 
        let catSql = `update cnt_article set ${cn} = '${cv}' where article_id='${article_id}'    `  ;

        //输出到前端  
        r.cats = yield this._daoModel.query(catSql);

        return {
            code: 200,
            successed: true, 
            cats:r.cats.rows,
            msg:"修改成功"
        }
    }

    verify_login(instance, result, req, res) {
        let result_rows = JSON.parse(JSON.stringify(result.rows))[0]
        let user_id = 0
        let result_rows2 = JSON.parse(JSON.stringify(result.rows))[1]
        let msg = '登录成功';
        let id = req.body.pid               //楼盘id或管家id
        let pid = '0'                      //楼盘id
        let keepId = '0'                  //管家id
        let strId = id.toString()
        if (strId.length < 15) {
            pid = id
        } else {
            keepId = id
        }
        let type = req.body.type || '3'           //1为收藏=>收藏成功，2为免费咨询管家=>msg，3为楼盘免费咨询（专车接送）=>msg，4为户型免费咨询（专车接送）=>msg
        let today = date.format(new Date(), 'YYYY-MM-DD HH:mm:ss'); //实时时间
        let buildSql = ''
        let hxId = req.body.hxid || '0';    //户型id
        let jjx = req.body.jjx;             //几居
        let mj = req.body.mj || '0';        //户型面积
        let city = req.body.city

        //默认接入佛山接口
        let apiUrl = "http://www.fangkejia.com/jiwuyun/face/customer/access/074bcb138a9277b3"
        if (city == "佛山市") {
            apiUrl = "http://www.fangkejia.com/jiwuyun/face/customer/access/074bcb138a9277b3"
        } else if (city == "肇庆市") {
            apiUrl = "http://www.fangkejia.com/jiwuyun/face/customer/access/47f388851f1ea99d"
        } else {
            apiUrl = "http://www.fangkejia.com/jiwuyun/face/customer/access/074bcb138a9277b3"
        }

        //根据传入type判断执行对应语句
        function dealSql(user_id, pid, today, type, hxId, keepId) {
            if (type == '0') {
                buildSql = '1'
                msg = '登录成功.'

            } else if (type == '1') {
                buildSql = `INSERT INTO home_favor_item(uid,pid,like_time) VALUES('${user_id}','${pid}','${today}')`
                msg = '收藏成功.'

            } else if (type == '2') {
                buildSql = `INSERT INTO crm_user_build(uid,build_id,ask_time) VALUES('${user_id}','${keepId}','${today}')`
                msg = '谢谢!稍后我们的置业管家会亲自联系您,请耐心等候.'

            } else if (type == '3') {
                buildSql = `INSERT INTO crm_user_build(uid,build_id,ask_time) VALUES('${user_id}','${pid}','${today}')`
                msg = '谢谢!稍后我们的置业管家会亲自联系您,请耐心等候.'

            } else if (type == '4') {
                buildSql = `INSERT INTO crm_user_build(uid,build_id,ask_time,lphx_id) VALUES('${user_id}','${pid}','${today}','${hxId}')`
                msg = '谢谢!稍后我们的置业管家会亲自联系您,请耐心等候.'

            } else {
                buildSql = '1'
                msg = '操作成功.'

            }

            return { buildSql, msg }
        }

        //房客家进线
        function toFangKeJia(pid, user_mobile) {
            if (pid && pid != '0') {

                let houseql = `SELECT sq,qy,name FROM home_base WHERE id='${pid}'`
                instance._daoModel.query(houseql).then(houseResult => {
                    let house = houseResult.rows[0]
                    if (house) {
                        //意向城市
                        let intentionCity = house.sq
                        //意向区域
                        let intentionArea = house.qy
                        intentionArea = intentionArea.substring(0, intentionArea.length - 1)
                        //意向楼盘
                        let intentionBuild = house.name
                        //意向户型
                        let intentionType = '待定'
                        //意向面积
                        let intentionMj = '待定'

                        if (intentionCity == "佛山市") {
                            apiUrl = "http://www.fangkejia.com/jiwuyun/face/customer/access/074bcb138a9277b3"
                        } else if (intentionCity == "肇庆市") {
                            apiUrl = "http://www.fangkejia.com/jiwuyun/face/customer/access/47f388851f1ea99d"
                        } else {
                            apiUrl = "http://www.fangkejia.com/jiwuyun/face/customer/access/074bcb138a9277b3"
                        }
                        if (jjx && jjx != 0) {
                            if (jjx == '1') {
                                intentionType = '一室'
                            } else if (jjx == '2') {
                                intentionType = '二室'
                            } else if (jjx == '3') {
                                intentionType = '三室'
                            } else if (jjx == '4') {
                                intentionType = '四室'
                            } else if (jjx >= '5') {
                                intentionType = '五室及以上'
                            } else {
                                intentionType = '待定'
                            }
                            intentionMj = '0㎡-' + mj + '㎡'
                        } else {
                            intentionType = '待定'
                        }

                        var apiData = rpc.request({
                            url: apiUrl,
                            method: 'POST',
                            body: JSON.stringify({
                                "trueName": "官网用户",
                                "mobile": user_mobile,
                                "sex": "待定",
                                "intentionLevel": "待定",
                                "buyQualification": "待定",
                                "buyPurpose": "待定",
                                "loanQuota": "待定",
                                "age": "待定",
                                "intentionPrice": "待定",
                                "intentionbuild": intentionBuild,
                                "intentionarea": intentionArea,
                                "intentionHouse": intentionType,
                                "intentionAreaMinMax": intentionMj,
                                "renovationType": "待定"
                            }),
                            headers: {
                                'Content-Type': 'application/json'
                            }
                        }).then(function (ApiData) {
                            ApiData = ApiData.toString('uft-8');
                            ApiData = JSON.parse(ApiData)
                            console.log(ApiData)
                        });
                    } else {
                        var apiData = rpc.request({
                            url: apiUrl,
                            method: 'POST',
                            body: JSON.stringify({
                                "trueName": "官网用户",
                                "mobile": user_mobile,
                                "sex": "待定",
                                "intentionLevel": "待定",
                                "buyQualification": "待定",
                                "buyPurpose": "待定",
                                "loanQuota": "待定",
                                "age": "待定",
                                "intentionPrice": "待定",
                                "intentionbuild": "待定",
                                "intentionarea": "待定",
                                "intentionHouse": "待定",
                                "intentionAreaMinMax": "待定",
                                "renovationType": "待定"
                            }),
                            headers: {
                                'Content-Type': 'application/json'
                            }
                        }).then(function (ApiData) {
                            ApiData = ApiData.toString('uft-8');
                            ApiData = JSON.parse(ApiData)
                            console.log(ApiData)
                        });
                    }
                })
            } else {
                var apiData = rpc.request({
                    url: apiUrl,
                    method: 'POST',
                    body: JSON.stringify({
                        "trueName": "官网用户",
                        "mobile": user_mobile,
                        "sex": "待定",
                        "intentionLevel": "待定",
                        "buyQualification": "待定",
                        "buyPurpose": "待定",
                        "loanQuota": "待定",
                        "age": "待定",
                        "intentionPrice": "待定",
                        "intentionbuild": "待定",
                        "intentionarea": "待定",
                        "intentionHouse": "待定",
                        "intentionAreaMinMax": "待定",
                        "renovationType": "待定"
                    }),
                    headers: {
                        'Content-Type': 'application/json'
                    }
                }).then(function (ApiData) {
                    ApiData = ApiData.toString('uft-8');
                    ApiData = JSON.parse(ApiData)
                    console.log(ApiData)
                });
            }
        }

        if (result_rows.length == 0) {                                         // 数据库里面没有该手机的记录就进行注册
            if (result_rows2.length != 0) {
                let clas = result_rows2[0]
                let user_id = clas.user_id;
                let user_mobile = clas.user_mobile;
                let user_name = clas.user_name;
                let user_image = clas.user_image;

                let today = date.format(new Date(), 'YYYY-MM-DD HH:mm:ss');
                let sql = `UPDATE crm_user SET khzxsj='${today}' WHERE user_id='${user_id}'`
                if (pid) {
                    sql = `UPDATE crm_user SET khzxsj='${today}',city=(SELECT sq FROM home_base a WHERE a.id='${pid}'),lp_id='${pid}',yxqy=(SELECT qy FROM home_base a WHERE a.id='${pid}') WHERE user_id='${user_id}';`;
                }
                if (hxId && hxId != '0') {
                    sql = `UPDATE crm_user SET khzxsj='${today}',city=(SELECT a.sq FROM home_base a INNER JOIN home_base_hx b ON b.pid=a.id WHERE b.id='${hxId}'),lp_id=(SELECT pid FROM home_base_hx WHERE id='${hxId}'),yxqy=(SELECT a.qy FROM home_base a INNER JOIN home_base_hx b ON b.pid=a.id WHERE b.id='${hxId}'),hx_id='${hxId}' WHERE user_id='${user_id}';`;
                }
                let dal = new memberDao();
                dal.query(sql).catch(function (err) {

                });
                //房客家进线
                toFangKeJia(pid, user_mobile)

                let resSql = dealSql(user_id, pid, today, type, hxId, keepId)
                if (resSql.buildSql != '') {
                    if (resSql.buildSql != '1') {
                        instance._daoModel.query(buildSql).then(buildResult => {
                            if (type == '2' || type == '3' || type == '4') {
                                msg = resSql.msg + "业务流水号:" + buildResult.rows.insertId
                            } else {
                                msg = resSql.msg
                            }
                            res.json({ successed: true, user_id: user_id, user_name: user_name, user_image: user_image, msg: msg })
                        })
                    } else {
                        msg = resSql.msg
                        res.json({ successed: true, user_id: user_id, user_name: user_name, user_image: user_image, msg: msg })
                    }
                }

            } else {
                let khly = req.body.khly || '1';
                let user_mobile = req.body.user_mobile
                let puid = req.body.puid;
                let user_name = "用户_" + user_mobile
                let user_id = UUID.v1();
                let user_sex = '1'
                let user_create_date = new Date(Date.now() + (8 * 60 * 60 * 1000)).toISOString().replace('T', ' ').split('.')[0]
                let user_serial = 0
                co(instance._daoModel.loadData("select fun_GetSerial()"))
                    .then(result => {
                        user_serial = JSON.parse(JSON.stringify(result.rows))[0]['fun_GetSerial()']
                        console.log(user_id, user_name, user_sex, user_create_date, user_serial)
                        if (!puid) {
                            puid = ''
                        }
                        let inser_crm_user = "insert into crm_user (user_image,user_id,user_name,user_sex,user_create_date,user_serial,user_mobile,puid,khscsj,khzxsj,ydscsj) values ('http://image.xinghe00.com/user_image.jpg'," + "'" + user_id + "'" + "," + "'" + user_name + "'" + "," + user_sex + "," + "'" + user_create_date + "'" + "," + "'" + user_serial + "'" + "," + "'" + user_mobile + "','" + puid + "'" + ",'" + user_create_date + "'" + ",'" + user_create_date + "'" + ",'" + user_create_date + "'" + ')'
                        if (khly) {
                            inser_crm_user = "insert into crm_user (user_image,user_id,user_name,user_sex,user_create_date,user_serial,user_mobile,puid,khly,khscsj,khzxsj,ydscsj) values ('http://image.xinghe00.com/user_image.jpg'," + "'" + user_id + "'" + "," + "'" + user_name + "'" + "," + user_sex + "," + "'" + user_create_date + "'" + "," + "'" + user_serial + "'" + "," + "'" + user_mobile + "','" + puid + "','" + khly + "'" + ",'" + user_create_date + "'" + ",'" + user_create_date + "'" + ",'" + user_create_date + "'" + ')'
                            if (pid) {
                                inser_crm_user = "insert into crm_user (user_image,user_id,user_name,user_sex,user_create_date,user_serial,user_mobile,puid,khly,khscsj,khzxsj,ydscsj,lp_id,city,yxqy) values ('http://image.xinghe00.com/user_image.jpg'," + "'" + user_id + "'" + "," + "'" + user_name + "'" + "," + user_sex + "," + "'" + user_create_date + "'" + "," + "'" + user_serial + "'" + "," + "'" + user_mobile + "','" + puid + "','" + khly + "'" + ",'" + user_create_date + "'" + ",'" + user_create_date + "'" + ",'" + user_create_date + "'" + ",'" + pid + "'" + ",(SELECT sq FROM home_base a WHERE a.id='" + pid + "'),(SELECT qy FROM home_base a WHERE a.id='" + pid + "')" + ')';
                            }
                            if (hxId && hxId != '0') {
                                inser_crm_user = "insert into crm_user (user_image,user_id,user_name,user_sex,user_create_date,user_serial,user_mobile,puid,khly,khscsj,khzxsj,ydscsj,lp_id,city,yxqy,hx_id) values ('http://image.xinghe00.com/user_image.jpg'," + "'" + user_id + "'" + "," + "'" + user_name + "'" + "," + user_sex + "," + "'" + user_create_date + "'" + "," + "'" + user_serial + "'" + "," + "'" + user_mobile + "','" + puid + "','" + khly + "'" + ",'" + user_create_date + "'" + ",'" + user_create_date + "'" + ",'" + user_create_date + "',(SELECT pid FROM home_base_hx WHERE id='" + hxId + "'),(SELECT a.sq FROM home_base a INNER JOIN home_base_hx b ON b.pid=a.id WHERE b.id='" + hxId + "'),(SELECT a.qy FROM home_base a INNER JOIN home_base_hx b ON b.pid=a.id WHERE b.id='" + hxId + "'),'" + hxId + "'" + ')';
                            }
                        }


                        //房客家进线
                        toFangKeJia(pid, user_mobile)

                        let resSql = dealSql(user_id, pid, today, type, hxId, keepId)
                        if (resSql.buildSql != '') {
                            if (resSql.buildSql != '1') {
                                instance._daoModel.query(buildSql).then(buildResult => {
                                    if (type == '2' || type == '3' || type == '4') {
                                        console.log(msg, "================================1");
                                        msg = resSql.msg + "业务流水号:" + buildResult.rows.insertId
                                        console.log(msg, "================================2");
                                    } else {
                                        msg = resSql.msg
                                    }
                                    co(instance._daoModel.loadData(inser_crm_user))
                                        .then(res.json({ successed: true, user_id: user_id, user_name: user_name, user_image: 'http://image.xinghe00.com/user_image.jpg', msg: msg }))
                                })
                            } else {
                                msg = resSql.msg
                                co(instance._daoModel.loadData(inser_crm_user))
                                    .then(res.json({ successed: true, user_id: user_id, user_name: user_name, user_image: 'http://image.xinghe00.com/user_image.jpg', msg: msg }))
                            }
                        }

                    })
            }
        }
        else {
            let today = date.format(new Date(), 'YYYY-MM-DD HH:mm:ss');
            user_id = result_rows[0].user_id
            let user_mobile = req.body.user_mobile
            let sql = `UPDATE crm_user SET khzxsj='${today}' WHERE user_id='${user_id}'`
            if (pid) {
                sql = `UPDATE crm_user SET khzxsj='${today}',city=(SELECT sq FROM home_base a WHERE a.id='${pid}'),lp_id='${pid}',yxqy=(SELECT qy FROM home_base a WHERE a.id='${pid}') WHERE user_id='${user_id}';`;
            }
            if (hxId && hxId != '0') {
                sql = `UPDATE crm_user SET khzxsj='${today}',city=(SELECT a.sq FROM home_base a INNER JOIN home_base_hx b ON b.pid=a.id WHERE b.id='${hxId}'),lp_id=(SELECT pid FROM home_base_hx WHERE id='${hxId}'),yxqy=(SELECT a.qy FROM home_base a INNER JOIN home_base_hx b ON b.pid=a.id WHERE b.id='${hxId}'),hx_id='${hxId}' WHERE user_id='${user_id}';`;
            }
            let dal = new memberDao();
            dal.query(sql).catch(function (err) {

            });
            let user_name = result_rows[0].user_name
            let user_image = result_rows[0].user_image

            //房客家进线
            toFangKeJia(pid, user_mobile)

            let resSql = dealSql(user_id, pid, today, type, hxId, keepId)
            if (resSql.buildSql != '') {
                if (resSql.buildSql != '1') {
                    instance._daoModel.query(buildSql).then(buildResult => {
                        if (type == '2' || type == '3' || type == '4') {
                            msg = resSql.msg + "业务流水号:" + buildResult.rows.insertId
                        } else {
                            msg = resSql.msg
                        }
                        res.json({ successed: true, user_id: user_id, user_name: user_name, user_image: user_image, msg: msg })
                    })
                } else {
                    msg = resSql.msg
                    res.json({ successed: true, user_id: user_id, user_name: user_name, user_image: user_image, msg: msg })
                }
            }
        }
    }

    * addFavorItem(req, res) {
        let pid = req.body.pid;
        let uid = req.body.uid;
        // return {pid:pid,uid:uid,pid1:pid1,uid1:uid1}
        if (pid && uid) {
            //获取手机号
            let sqlUser_mobile = `select user_id,user_mobile from crm_user where user_id='${uid}'`
            let resultUser_mobile = yield this._daoModel.query(sqlUser_mobile);
            let user_mobileArr = resultUser_mobile.rows[0]
            let userMobile = user_mobileArr.user_mobile;
            let sqlFavorItem = ``;
            if (userMobile) {
                sqlFavorItem = `select count(1) num from home_favor_item a where a.pid=${pid} and a.uid in (SELECT user_id from crm_user where user_mobile=(SELECT user_mobile FROM crm_user where user_id='${uid}'))`
            } else {
                sqlFavorItem = `select count(1) num from home_favor_item a where a.pid=${pid} and a.uid='${uid}'`
            }
            let resultFavorItem = yield this._daoModel.query(sqlFavorItem);
            let arrFavorItem = resultFavorItem.rows[0]
            if (arrFavorItem.num > 0) {
                return { code: 0, successed: true, msg: "已收藏" }
            }
            let today = date.format(new Date(), 'YYYY-MM-DD HH:mm:ss');
            let sql = `INSERT INTO home_favor_item(pid,uid,like_time) VALUES(${pid},'${uid}','${today}')`
            let result = yield this._daoModel.query(sql);
            if (result.rows.affectedRows) {
                return { code: 1, successed: true, msg: "收藏成功" }
            } else {
                return { code: 0, successed: false, msg: "收藏失败" }
            }
        } else {
            return { code: 0, successed: false, msg: "收藏失败" }
        }
    }

    * delFavorItem(req, res) {
        let pid = req.body.pid;
        let uid = req.body.uid;
        if (pid && uid) {
            //获取手机号
            let sqlUser_mobile = `select user_id,user_mobile from crm_user where user_id='${uid}'`
            let resultUser_mobile = yield this._daoModel.query(sqlUser_mobile);
            let user_mobileArr = resultUser_mobile.rows[0]
            let userMobile = user_mobileArr.user_mobile;
            if (userMobile) {
                let sqlUserID = `SELECT user_id from crm_user where user_mobile=(SELECT user_mobile FROM crm_user where user_id='${uid}')`
                let resultUserID = yield this._daoModel.query(sqlUserID);
                let userIdArr = resultUserID.rows
                // return {userIdArr:userIdArr}
                for (let i = 0; i < userIdArr.length; i++) {
                    let userid = userIdArr[i].user_id;
                    let sql = `DELETE FROM home_favor_item where pid=${pid} and uid='${userid}'`
                    let result = yield this._daoModel.query(sql);
                }
                return { code: 1, successed: true, msg: "已取消收藏" }
            } else {
                let sql = `DELETE FROM home_favor_item where pid=${pid} and uid='${uid}'`
                let result = yield this._daoModel.query(sql);
                if (result.rows.affectedRows) {
                    return { code: 1, successed: true, msg: "已取消收藏" }
                } else {
                    return { code: 0, successed: false, msg: "取消失败" }
                }
            }
        } else {
            return { code: 0, successed: false, msg: "取消失败" }
        }
    }


    //获取浏览楼盘信息
    * getSeeItemList(req) {
        let r = {};
        let uid = req.query.uid;
        //从配置类获取请求头前缀
        let httpHead = config.appsetting.picHead
        // uid='58131f81-02e3-4538-95cc-c6f2dab3cd22'

        //获取手机号
        let sqlUser_mobile = `SELECT user_id,user_mobile FROM crm_user WHERE user_id='${uid}'`
        let resultUser_mobile = yield this._daoModel.query(sqlUser_mobile);
        let user_mobileArr = resultUser_mobile.rows[0]
        let userMobile = user_mobileArr.user_mobile;

        // 返回楼盘信息
        let sql_home_base = `SELECT SQL_CALC_FOUND_ROWS DISTINCT a.id aid,a.see_time,b.lon,b.lat,b.id,b.pics,b.xszt,b.name,b.address,b.qy,b.xsjg,d.name jzlxname,f.name wylxname
        FROM home_see_item a
           LEFT JOIN home_base b ON b.id=a.pid
           LEFT JOIN home_base_hx c ON c.pid=b.id
           LEFT JOIN home_jzlx d ON d.id=b.jzlx_id
           LEFT JOIN home_wylx f ON f.id=b.wylx_id
           WHERE  a.uid IN (SELECT user_id FROM crm_user WHERE user_mobile=(SELECT user_mobile FROM crm_user WHERE user_id='${uid}'))
          ORDER BY a.see_time DESC;SELECT FOUND_ROWS() num;`;

        if (!userMobile) {
            sql_home_base = `SELECT SQL_CALC_FOUND_ROWS DISTINCT a.id aid,a.see_time,b.lon,b.lat,b.id,b.pics,b.xszt,b.name,b.address,b.qy,b.xsjg,d.name jzlxname,f.name wylxname
            FROM home_see_item a
           LEFT JOIN home_base b ON b.id=a.pid
           LEFT JOIN home_base_hx c ON c.pid=b.id
           LEFT JOIN home_jzlx d ON d.id=b.jzlx_id
           LEFT JOIN home_wylx f ON f.id=b.wylx_id
           WHERE  a.uid ='${uid}'
          ORDER BY a.see_time DESC;SELECT FOUND_ROWS() num;`;
        }


        let result_home_base = yield this._daoModel.query(sql_home_base);
        let arrHomeBase = result_home_base.rows[0]
        let homeBaseCount = result_home_base.rows[1]
        r.homeBaseCount = homeBaseCount[0].num
        let arrHomeBaseId = []
        let arrFavorID = []//接收收藏的楼盘id
        //收藏楼盘标识
        if (uid) {
            let sqlFavorItem = ``;
            if (userMobile) {
                sqlFavorItem = `SELECT a.pid FROM home_favor_item a WHERE a.uid IN (SELECT user_id FROM crm_user WHERE user_mobile=(SELECT user_mobile FROM crm_user WHERE user_id='${uid}'))`
            } else {
                sqlFavorItem = `SELECT a.pid FROM home_favor_item a WHERE a.uid='${uid}'`
            }
            let resultFavorItem = yield this._daoModel.query(sqlFavorItem);
            arrFavorID = resultFavorItem.rows
            // r.arrFavorItem = arrFavorID
        }
        for (let i = 0; i < arrHomeBase.length; i++) {
            if (arrHomeBase[i].pics) {
                let a = arrHomeBase[i].pics.substring(0, 4)
                //判断有没有http前缀
                if (a != 'http') {
                    arrHomeBase[i].pics = httpHead + arrHomeBase[i].pics
                }
            }
            if (arrHomeBase[i].xsjg == 0) {
                arrHomeBase[i].xsjg = '暂无均价'
            } else {
                let a = arrHomeBase[i].xsjg
                arrHomeBase[i].xsjg = a + '元/m²'
            }



            // //查询最大建筑面积、参考总价和最小建筑面积、参考总价
            // let ttid = arrHomeBase[i].id
            // let sql_maxAndMin = `select MAX(jzmj) maxJzmj,MIN(jzmj) minJzmj,MAX(ckzj) maxCkzj,MIN(ckzj) minCkzj from home_base_hx where pid=${ttid}  and xszt='0' and del=0`;
            // let result_maxAndMin = yield this._daoModel.query(sql_maxAndMin);
            // let arrMaxAndMin = result_maxAndMin.rows[0]
            // // arrHomeBase.jzmjAndCkzj = arrMaxAndMin

            // let strJzmj = '待定'
            // let strCkzj = '待定'
            // if (arrMaxAndMin) {
            //     //建筑面积 
            //     if (arrMaxAndMin.minJzmj > 0 && arrMaxAndMin.maxJzmj > 0) {
            //         strJzmj = parseInt(arrMaxAndMin.minJzmj) + '-' + parseInt(arrMaxAndMin.maxJzmj) + 'm²'
            //     }
            //     //参考总价
            //     if (arrMaxAndMin.minCkzj > 0 && arrMaxAndMin.maxCkzj > 0) {
            //         strCkzj = parseInt(arrMaxAndMin.minCkzj) + '-' + parseInt(arrMaxAndMin.maxCkzj) + '万'
            //     }
            // }
            // arrHomeBase[i].strJzmj = strJzmj
            // arrHomeBase[i].strCkzj = strCkzj


            //#待删除
            //查询最大建筑面积、参考总价和最小建筑面积、参考总价
            let ttid = arrHomeBase[i].id
            let sql_maxAndMin = `SELECT total_min minCkzj,total_max maxCkzj,mianji_min minJzmj,mianji_max maxJzmj FROM home_base WHERE id=${ttid}`;
            let result_maxAndMin = yield this._daoModel.query(sql_maxAndMin);
            let arrMaxAndMintt = result_maxAndMin.rows[0]
            if (arrMaxAndMintt.maxJzmj > 0 && arrMaxAndMintt.minJzmj > 0) {
                arrMaxAndMintt.maxJzmj = parseInt(arrMaxAndMintt.maxJzmj)
                arrMaxAndMintt.minJzmj = parseInt(arrMaxAndMintt.minJzmj)
            } else {
                arrMaxAndMintt.maxJzmj = '待定'
                arrMaxAndMintt.minJzmj = '待定'
            }
            if (arrMaxAndMintt.maxCkzj > 0 && arrMaxAndMintt.minCkzj > 0) {
                arrMaxAndMintt.maxCkzj = parseInt(arrMaxAndMintt.maxCkzj)
                arrMaxAndMintt.minCkzj = parseInt(arrMaxAndMintt.minCkzj)
            } else {
                arrMaxAndMintt.maxCkzj = '待定'
                arrMaxAndMintt.minCkzj = '待定'
            }
            let arrMaxAndMin = {
                "maxJzmj": arrMaxAndMintt.maxJzmj,
                "minJzmj": arrMaxAndMintt.minJzmj,
                "maxCkzj": arrMaxAndMintt.maxCkzj,
                "minCkzj": arrMaxAndMintt.minCkzj
            }
            arrHomeBase[i].jzmjAndCkzj = arrMaxAndMin

            //建筑面积
            let strJzmj = parseInt(arrMaxAndMintt.minJzmj) + '-' + parseInt(arrMaxAndMintt.maxJzmj) + 'm²'
            if (arrMaxAndMintt.minJzmj == '待定' || arrMaxAndMintt.maxJzmj == '待定' || arrMaxAndMintt.minJzmj == 0 || arrMaxAndMintt.maxJzmj == 0 || arrMaxAndMintt.minJzmj == "null" || arrMaxAndMintt.maxJzmj == "null") {
                strJzmj = '待定'
            }
            arrHomeBase[i].strJzmj = strJzmj
            //参考总价
            let strCkzj = arrMaxAndMintt.minCkzj + '-' + arrMaxAndMintt.maxCkzj + '万'
            if (arrMaxAndMintt.minCkzj == '待定' || arrMaxAndMintt.maxCkzj == '待定' || arrMaxAndMintt.minCkzj == 0 || arrMaxAndMintt.maxCkzj == 0 || arrMaxAndMintt.minCkzj == "null" || arrMaxAndMintt.maxCkzj == "null") {
                strCkzj = '待定'
            }
            arrHomeBase[i].strCkzj = strCkzj
            //#待删除


            //查询楼盘标签
            arrHomeBaseId.push(arrHomeBase[i].id)
            //标识用户是否收藏
            arrHomeBase[i].isSC = false
            for (let a = 0; a < arrFavorID.length; a++) {
                let rxid = arrHomeBase[i].id
                let fid = arrFavorID[a].pid
                if (rxid == fid) {
                    arrHomeBase[i].isSC = true
                }
            }
        }
        //查询楼盘标签
        if (arrHomeBaseId.length > 0) {
            let homeBaseIdArr = '('
            for (let i = 0; i < arrHomeBaseId.length; i++) {
                if (i == 0) {
                    homeBaseIdArr += arrHomeBaseId[i]
                } else {
                    homeBaseIdArr += ',' + arrHomeBaseId[i]
                }
            }
            homeBaseIdArr += ')'
            let sql_homeLabel = `SELECT a.label_id,a.label_name,b.home_id
            FROM bas_label a INNER JOIN home_label b ON a.label_id=b.label_id
            WHERE a.label_disabled=0 AND b.home_id IN ${homeBaseIdArr}`;
            let result_homeLabel = yield this._daoModel.query(sql_homeLabel);
            let arrHomeLabel = result_homeLabel.rows

            for (let i = 0; i < arrHomeBase.length; i++) {
                let hbId = arrHomeBase[i].id
                let homeLabelList = []
                let homeLabel = {}
                for (let a = 0; a < arrHomeLabel.length; a++) {
                    let home_id = arrHomeLabel[a].home_id
                    if (hbId == home_id) {
                        homeLabel = {
                            "label_id": arrHomeLabel[a].label_id,
                            "label_name": arrHomeLabel[a].label_name,
                            "home_id": arrHomeLabel[a].home_id
                        };
                        homeLabelList.push(homeLabel)
                    }
                }
                arrHomeBase[i].arrHomeLabel = homeLabelList
            }

            //楼盘信息添加楼盘居室
            let sql_homejjx = `SELECT DISTINCT a.id,b.jjx
            FROM home_base a INNER JOIN home_base_hx b ON b.pid=a.id
            WHERE b.xszt='0' AND b.del=0 AND a.id IN ${homeBaseIdArr}`;
            let result_homejjx = yield this._daoModel.query(sql_homejjx);
            let arrHomeJS = result_homejjx.rows
            for (let i = 0; i < arrHomeBase.length; i++) {
                let hbId = arrHomeBase[i].id
                let homeJSList = []
                let homeJS = {}
                for (let a = 0; a < arrHomeJS.length; a++) {
                    let home_id = arrHomeJS[a].id
                    if (hbId == home_id) {
                        homeJS = {
                            "id": arrHomeJS[a].id,
                            "jjx": arrHomeJS[a].jjx
                        };
                        homeJSList.push(homeJS)
                    }
                }
                arrHomeBase[i].arrHomeJS = homeJSList
            }
        }
        r.HomeBaseList = arrHomeBase
        return { code: 1, successed: true, rows: r };
    }

    //获取收藏楼盘信息
    * getFavorItemList(req) {
        let r = {};
        let uid = req.query.uid;
        //从配置类获取请求头前缀
        let httpHead = config.appsetting.picHead
        // uid='58131f81-02e3-4538-95cc-c6f2dab3cd22'

        //获取手机号
        let sqlUser_mobile = `SELECT user_id,user_mobile FROM crm_user WHERE user_id='${uid}'`
        let resultUser_mobile = yield this._daoModel.query(sqlUser_mobile);
        let user_mobileArr = resultUser_mobile.rows[0]
        let userMobile = user_mobileArr.user_mobile;

        // 返回楼盘信息
        let sql_home_base = `SELECT SQL_CALC_FOUND_ROWS DISTINCT a.id aid,a.like_time,b.lon,b.lat,b.id,b.pics,b.xszt,b.name,b.address,b.qy,b.xsjg,d.name jzlxname,f.name wylxname
        FROM home_favor_item a
           LEFT JOIN home_base b ON b.id=a.pid
           LEFT JOIN home_base_hx c ON c.pid=b.id
           LEFT JOIN home_jzlx d ON d.id=b.jzlx_id
           LEFT JOIN home_wylx f ON f.id=b.wylx_id
           WHERE  a.uid in (SELECT user_id FROM crm_user WHERE user_mobile=(SELECT user_mobile FROM crm_user WHERE user_id='${uid}'))
          ORDER BY a.like_time DESC;SELECT FOUND_ROWS() num;`;

        if (!userMobile) {
            sql_home_base = `SELECT SQL_CALC_FOUND_ROWS DISTINCT a.id aid,a.like_time,b.lon,b.lat,b.id,b.pics,b.xszt,b.name,b.address,b.qy,b.xsjg,d.name jzlxname,f.name wylxname
            FROM home_favor_item a
           LEFT JOIN home_base b ON b.id=a.pid
           LEFT JOIN home_base_hx c ON c.pid=b.id
           LEFT JOIN home_jzlx d ON d.id=b.jzlx_id
           LEFT JOIN home_wylx f ON f.id=b.wylx_id
           WHERE  a.uid ='${uid}'
          ORDER BY a.like_time DESC;SELECT FOUND_ROWS() num;`;
        }


        let result_home_base = yield this._daoModel.query(sql_home_base);
        let arrHomeBase = result_home_base.rows[0]
        let homeBaseCount = result_home_base.rows[1]
        r.homeBaseCount = homeBaseCount[0].num
        let arrHomeBaseId = []
        let arrFavorID = []//接收收藏的楼盘id
        //收藏楼盘标识
        if (uid) {
            let sqlFavorItem = ``;
            if (userMobile) {
                sqlFavorItem = `SELECT a.pid FROM home_favor_item a WHERE a.uid IN (SELECT user_id FROM crm_user WHERE user_mobile=(SELECT user_mobile FROM crm_user WHERE user_id='${uid}'))`
            } else {
                sqlFavorItem = `SELECT a.pid FROM home_favor_item a WHERE a.uid='${uid}'`
            }
            // return {sqlFavorItem:sqlFavorItem}
            let resultFavorItem = yield this._daoModel.query(sqlFavorItem);
            arrFavorID = resultFavorItem.rows
            // r.arrFavorItem = arrFavorID
        }
        for (let i = 0; i < arrHomeBase.length; i++) {
            if (arrHomeBase[i].pics) {
                let a = arrHomeBase[i].pics.substring(0, 4)
                //判断有没有http前缀
                if (a != 'http') {
                    arrHomeBase[i].pics = httpHead + arrHomeBase[i].pics
                }
            }
            if (arrHomeBase[i].xsjg == 0) {
                arrHomeBase[i].xsjg = '暂无均价'
            } else {
                let a = arrHomeBase[i].xsjg
                arrHomeBase[i].xsjg = a + '元/m²'
            }


            // //查询最大建筑面积、参考总价和最小建筑面积、参考总价
            // let ttid = arrHomeBase[i].id
            // let sql_maxAndMin = `select MAX(jzmj) maxJzmj,MIN(jzmj) minJzmj,MAX(ckzj) maxCkzj,MIN(ckzj) minCkzj from home_base_hx where pid=${ttid}  and xszt='0' and del=0`;
            // let result_maxAndMin = yield this._daoModel.query(sql_maxAndMin);
            // let arrMaxAndMin = result_maxAndMin.rows[0]
            // // arrHomeBase.jzmjAndCkzj = arrMaxAndMin

            // let strJzmj = '待定'
            // let strCkzj = '待定'
            // if (arrMaxAndMin) {
            //     //建筑面积 
            //     if (arrMaxAndMin.minJzmj > 0 && arrMaxAndMin.maxJzmj > 0) {
            //         strJzmj = parseInt(arrMaxAndMin.minJzmj) + '-' + parseInt(arrMaxAndMin.maxJzmj) + 'm²'
            //     }
            //     //参考总价
            //     if (arrMaxAndMin.minCkzj > 0 && arrMaxAndMin.maxCkzj > 0) {
            //         strCkzj = parseInt(arrMaxAndMin.minCkzj) + '-' + parseInt(arrMaxAndMin.maxCkzj) + '万'
            //     }
            // }
            // arrHomeBase[i].strJzmj = strJzmj
            // arrHomeBase[i].strCkzj = strCkzj


            //#待删除
            //查询最大建筑面积、参考总价和最小建筑面积、参考总价
            let ttid = arrHomeBase[i].id
            let sql_maxAndMin = `SELECT total_min minCkzj,total_max maxCkzj,mianji_min minJzmj,mianji_max maxJzmj FROM home_base WHERE id=${ttid}`;
            let result_maxAndMin = yield this._daoModel.query(sql_maxAndMin);
            let arrMaxAndMintt = result_maxAndMin.rows[0]
            if (arrMaxAndMintt.maxJzmj > 0 && arrMaxAndMintt.minJzmj > 0) {
                arrMaxAndMintt.maxJzmj = parseInt(arrMaxAndMintt.maxJzmj)
                arrMaxAndMintt.minJzmj = parseInt(arrMaxAndMintt.minJzmj)
            } else {
                arrMaxAndMintt.maxJzmj = '待定'
                arrMaxAndMintt.minJzmj = '待定'
            }
            if (arrMaxAndMintt.maxCkzj > 0 && arrMaxAndMintt.minCkzj > 0) {
                arrMaxAndMintt.maxCkzj = parseInt(arrMaxAndMintt.maxCkzj)
                arrMaxAndMintt.minCkzj = parseInt(arrMaxAndMintt.minCkzj)
            } else {
                arrMaxAndMintt.maxCkzj = '待定'
                arrMaxAndMintt.minCkzj = '待定'
            }
            let arrMaxAndMin = {
                "maxJzmj": arrMaxAndMintt.maxJzmj,
                "minJzmj": arrMaxAndMintt.minJzmj,
                "maxCkzj": arrMaxAndMintt.maxCkzj,
                "minCkzj": arrMaxAndMintt.minCkzj
            }
            arrHomeBase[i].jzmjAndCkzj = arrMaxAndMin

            //建筑面积
            let strJzmj = parseInt(arrMaxAndMintt.minJzmj) + '-' + parseInt(arrMaxAndMintt.maxJzmj) + 'm²'
            if (arrMaxAndMintt.minJzmj == '待定' || arrMaxAndMintt.maxJzmj == '待定' || arrMaxAndMintt.minJzmj == 0 || arrMaxAndMintt.maxJzmj == 0 || arrMaxAndMintt.minJzmj == "null" || arrMaxAndMintt.maxJzmj == "null") {
                strJzmj = '待定'
            }
            arrHomeBase[i].strJzmj = strJzmj


            //参考总价
            let strCkzj = parseInt(arrMaxAndMintt.minCkzj) + '-' + parseInt(arrMaxAndMintt.maxCkzj) + '万'
            if (arrMaxAndMintt.minCkzj == '待定' || arrMaxAndMintt.maxCkzj == '待定' || arrMaxAndMintt.minCkzj == 0 || arrMaxAndMintt.maxCkzj == 0 || arrMaxAndMintt.minCkzj == "null" || arrMaxAndMintt.maxCkzj == "null") {
                strCkzj = '待定'
            }
            arrHomeBase[i].strCkzj = strCkzj
            //#待删除



            //查询楼盘标签
            arrHomeBaseId.push(arrHomeBase[i].id)
            //标识用户是否收藏
            arrHomeBase[i].isSC = false
            for (let a = 0; a < arrFavorID.length; a++) {
                let rxid = arrHomeBase[i].id
                let fid = arrFavorID[a].pid
                if (rxid == fid) {
                    arrHomeBase[i].isSC = true
                }
            }
        }
        //查询楼盘标签
        if (arrHomeBaseId.length > 0) {
            let homeBaseIdArr = '('
            for (let i = 0; i < arrHomeBaseId.length; i++) {
                if (i == 0) {
                    homeBaseIdArr += arrHomeBaseId[i]
                } else {
                    homeBaseIdArr += ',' + arrHomeBaseId[i]
                }
            }
            homeBaseIdArr += ')'
            let sql_homeLabel = `SELECT a.label_id,a.label_name,b.home_id
            FROM bas_label a INNER JOIN home_label b ON a.label_id=b.label_id
            WHERE a.label_disabled=0 AND b.home_id IN ${homeBaseIdArr}`;
            let result_homeLabel = yield this._daoModel.query(sql_homeLabel);
            let arrHomeLabel = result_homeLabel.rows

            for (let i = 0; i < arrHomeBase.length; i++) {
                let hbId = arrHomeBase[i].id
                let homeLabelList = []
                let homeLabel = {}
                for (let a = 0; a < arrHomeLabel.length; a++) {
                    let home_id = arrHomeLabel[a].home_id
                    if (hbId == home_id) {
                        homeLabel = {
                            "label_id": arrHomeLabel[a].label_id,
                            "label_name": arrHomeLabel[a].label_name,
                            "home_id": arrHomeLabel[a].home_id
                        };
                        homeLabelList.push(homeLabel)
                    }
                }
                arrHomeBase[i].arrHomeLabel = homeLabelList
            }

            //楼盘信息添加楼盘居室
            let sql_homejjx = `SELECT DISTINCT a.id,b.jjx
            FROM home_base a INNER JOIN home_base_hx b ON b.pid=a.id
            WHERE b.xszt='0'  AND b.del=0  AND a.id IN ${homeBaseIdArr}`;
            let result_homejjx = yield this._daoModel.query(sql_homejjx);
            let arrHomeJS = result_homejjx.rows
            for (let i = 0; i < arrHomeBase.length; i++) {
                let hbId = arrHomeBase[i].id
                let homeJSList = []
                let homeJS = {}
                for (let a = 0; a < arrHomeJS.length; a++) {
                    let home_id = arrHomeJS[a].id
                    if (hbId == home_id) {
                        homeJS = {
                            "id": arrHomeJS[a].id,
                            "jjx": arrHomeJS[a].jjx
                        };
                        homeJSList.push(homeJS)
                    }
                }
                arrHomeBase[i].arrHomeJS = homeJSList
            }
        }
        r.HomeBaseList = arrHomeBase
        return { code: 1, successed: true, rows: r };
    }


    //获取手机
    * getPhone(req, res) {
        let pid = req.body.pid || '0';
        let hxid = req.body.hxid || '0';
        let jjx = req.body.jjx;
        let mj = req.body.mj || '0';
        let uid = req.body.uid;
        let skey = req.body.skey;
        let iv = req.body.iv;
        let msg = '谢谢!稍后我们的置业管家会亲自联系您,请耐心等候.';
        let cloudID = req.body.cloudID;
        let today = date.format(new Date(), 'YYYY-MM-DD HH:mm:ss');
        //修改用户意向
        if (pid && pid != 0) {
            let sql = `SELECT id,sq,qy FROM home_base WHERE id='${pid}'`
            let result = yield this._daoModel.query(sql)
            let home = result.rows[0]
            if (home) {
                let sq = home.sq
                let qy = home.qy
                let updateSql = `UPDATE crm_user set city='${sq}',yxqy='${qy}',lp_id='${pid}' where user_id='${uid}'`
                let updateResult = yield this._daoModel.query(updateSql)

            }
        }

        // 已经获取过手机号的用户不用在获取手机号 只做插入crm_user_build和消息提醒
        if (iv == 0) {
            // 插入crm_user_build 用于追踪哪个楼盘或置业管家

            let insert_crm_user_build_sql = `INSERT INTO crm_user_build(uid,build_id,ask_time,lphx_id) VALUES('${uid}','${pid}','${today}','${hxid}')`
            let insert_crm_user_build_result = yield this._daoModel.query(insert_crm_user_build_sql)
            console.log("insert_crm_user_build_result.rows.insertId:" + insert_crm_user_build_result.rows.insertId)
            return { code: 1, successed: true, msg: msg + "业务类型号:" + iv + ",业务流水号:" + insert_crm_user_build_result.rows.insertId }
        }

        // 没获取过手机号的用户要获取手机号 同时插入crm_user_build和消息提醒
        let encryptedData = req.body.encryptedData;
        let decryptData = new WXBiZDataCrypt(config.wechat_mini.appID, skey)
        let deData = decryptData.decryptData(encryptedData, iv)
        let phoneNumber = deData.phoneNumber
        let sql = `select user_id,user_mobile,user_name from crm_user where user_id='${uid}'`
        let result = yield this._daoModel.query(sql);
        let user = result.rows[0]
        // let today = date.format(new Date(), 'YYYY-MM-DD HH:mm:ss');
        let sql_update_ydscsj = `UPDATE crm_user SET ydscsj='${today}' WHERE user_id='${uid}'`;//月度首次流资时间
        let result_update_ydscsj = yield this._daoModel.query(sql_update_ydscsj);
        let phoneSql = `select user_id,user_mobile from crm_user where user_mobile='${phoneNumber}'`
        let phoneResult = yield this._daoModel.query(phoneSql);
        let phone = phoneResult.rows[0]
        if (user) {
            // 插入crm_user_build 用于追踪哪个楼盘或置业管家
            let insert_crm_user_build_sql2 = `INSERT INTO crm_user_build(uid,build_id,ask_time) VALUES('${uid}',${pid},'${today}')`
            let insert_crm_user_build_result2 = yield this._daoModel.query(insert_crm_user_build_sql2);
            // return { code: 1, successed: true,uphone: phoneNumber, msg: msg+"业务流水号:"+insert_crm_user_build_result2.rows.insertId  }
            //修改手机号
            if (user.user_mobile != phoneNumber) {
                if (!phone) {
                    //默认接入佛山接口
                    let apiUrl = "http://www.fangkejia.com/jiwuyun/face/customer/access/074bcb138a9277b3"
                    //查询意向表、收藏表、足迹表的用户意向楼盘id
                    let buildSql = `select build_id pid from crm_user_build where uid = '${uid}'`
                    let favorSql = `select pid from home_favor_item where uid = '${uid}'`
                    let seeSql = `select pid from home_see_item where uid = '${uid}'`
                    let buildResult = yield this._daoModel.query(buildSql)
                    let favorResult = yield this._daoModel.query(favorSql)
                    let seeResult = yield this._daoModel.query(seeSql)
                    let build = buildResult.rows[0]
                    let favor = favorResult.rows[0]
                    let see = seeResult.rows[0]
                    let lpid = 0

                    if (pid && pid != 0) {
                        lpid = pid
                        console.log("000");
                    } else if (build && build.pid != 0) {
                        lpid = build.pid
                        console.log("111");
                    } else if (favor && favor.pid != 0) {
                        lpid = favor.pid
                        console.log("222");
                    } else if (see && see.pid != 0) {
                        lpid = see.pid
                        console.log("333");
                    } else {
                        lpid = 0
                        console.log("444");
                    }

                    if (lpid && lpid != 0) {
                        let houseSql = `SELECT sq,qy,name FROM home_base WHERE id='${lpid}'`
                        let houseResult = yield this._daoModel.query(houseSql)
                        let house = houseResult.rows[0]
                        if (house) {
                            //意向城市
                            let intentionCity = house.sq
                            //意向区域
                            let intentionArea = house.qy
                            intentionArea = intentionArea.substring(0, intentionArea.length - 1)
                            //意向楼盘
                            let intentionBuild = house.name
                            //意向户型
                            let intentionType = '待定'
                            //意向面积
                            let intentionMj = '待定'

                            if (intentionCity == "佛山市") {
                                apiUrl = "http://www.fangkejia.com/jiwuyun/face/customer/access/074bcb138a9277b3"
                            } else if (intentionCity == "肇庆市") {
                                apiUrl = "http://www.fangkejia.com/jiwuyun/face/customer/access/47f388851f1ea99d"
                            } else {
                                apiUrl = "http://www.fangkejia.com/jiwuyun/face/customer/access/074bcb138a9277b3"
                            }
                            if (jjx && jjx != 0) {
                                if (jjx == '1') {
                                    intentionType = '一室'
                                } else if (jjx == '2') {
                                    intentionType = '二室'
                                } else if (jjx == '3') {
                                    intentionType = '三室'
                                } else if (jjx == '4') {
                                    intentionType = '四室'
                                } else if (jjx >= '5') {
                                    intentionType = '五室及以上'
                                } else {
                                    intentionType = '待定'
                                }
                                intentionMj = '0㎡-' + mj + '㎡'
                            } else {
                                intentionType = '待定'
                            }
                            var apiData = yield rpc.request({
                                url: apiUrl,
                                method: 'POST',
                                body: JSON.stringify({
                                    "trueName": "官网用户",
                                    "mobile": phoneNumber,
                                    "sex": "待定",
                                    "intentionLevel": "待定",
                                    "buyQualification": "待定",
                                    "buyPurpose": "待定",
                                    "loanQuota": "待定",
                                    "age": "待定",
                                    "intentionPrice": "待定",
                                    "intentionbuild": intentionBuild,
                                    "intentionarea": intentionArea,
                                    "intentionHouse": intentionType,
                                    "intentionAreaMinMax": intentionMj,
                                    "renovationType": "待定"
                                }),
                                headers: {
                                    'Content-Type': 'application/json'
                                }
                            }).then(function (ApiData) {
                                ApiData = ApiData.toString('uft-8');
                                ApiData = JSON.parse(ApiData)
                                console.log(ApiData)
                            });
                        }
                    } else {
                        var apiData = yield rpc.request({
                            url: apiUrl,
                            method: 'POST',
                            body: JSON.stringify({
                                "trueName": "官网用户",
                                "mobile": phoneNumber,
                                "sex": "待定",
                                "intentionLevel": "待定",
                                "buyQualification": "待定",
                                "buyPurpose": "待定",
                                "loanQuota": "待定",
                                "age": "待定",
                                "intentionPrice": "待定",
                                "intentionbuild": "待定",
                                "intentionarea": "待定",
                                "intentionHouse": "待定",
                                "intentionAreaMinMax": "待定",
                                "renovationType": "待定"
                            }),
                            headers: {
                                'Content-Type': 'application/json'
                            }
                        }).then(function (ApiData) {
                            ApiData = ApiData.toString('uft-8');
                            ApiData = JSON.parse(ApiData)
                            console.log(ApiData)
                        });
                    }

                }
                let update_crm_user_sql = `UPDATE crm_user set user_mobile='${phoneNumber}',hx_id='${hxid}' where user_id='${uid}'`
                let update_crm_user_result = yield this._daoModel.query(update_crm_user_sql);
                return { code: 1, successed: true, uphone: phoneNumber, msg: msg + "业务流水号:" + insert_crm_user_build_result2.rows.insertId }
            } else {
                return { code: 1, successed: false, msg: "已通知置业管家," + msg }
            }

        }
        return { code: 1, successed: true, skey: skey, iv: iv, uphone: phoneNumber, msg: msg + "业务流水号:0000" }
    }



    //新增CrmUserBuild
    * addCrmUserBuild(req, res) {
        let id = req.body.pid               //楼盘id或管家id
        let pid                        //楼盘id
        let keepId                    //管家id
        let strId = id.toString()
        if (strId.length < 15) {
            pid = id
        } else {
            keepId = id
        }

        let uid = req.body.uid;
        let type = req.body.type || '3'           //1为收藏=>收藏成功，2为免费咨询管家=>msg，3为楼盘免费咨询（专车接送）=>msg，4为户型免费咨询（专车接送）=>msg
        let msg = '谢谢!稍后我们的置业管家会亲自联系您,请耐心等候.';
        let now = date.format(new Date(), 'YYYY-MM-DD HH:mm:ss'); //实时时间
        let buildSql = ''
        let hxId = req.body.hxid || '0';
        let jjx = req.body.jjx;
        let mj = req.body.mj || '0';
        let city = req.body.city

        function dealSql(user_id, pid, today, type, hxId, keepId) {
            if (type == '0') {
                buildSql = '1'
                msg = '操作成功.'

            } else if (type == '1') {
                buildSql = `INSERT INTO home_favor_item(uid,pid,like_time) VALUES('${user_id}','${pid}','${today}')`
                msg = '收藏成功.'

            } else if (type == '2') {
                buildSql = `INSERT INTO crm_user_build(uid,build_id,ask_time) VALUES('${user_id}','${keepId}','${today}')`
                msg = '谢谢!稍后我们的置业管家会亲自联系您,请耐心等候.'

            } else if (type == '3') {
                buildSql = `INSERT INTO crm_user_build(uid,build_id,ask_time) VALUES('${user_id}','${pid}','${today}')`
                msg = '谢谢!稍后我们的置业管家会亲自联系您,请耐心等候.'

            } else if (type == '4') {
                buildSql = `INSERT INTO crm_user_build(uid,build_id,ask_time,lphx_id) VALUES('${user_id}','${pid}','${today}','${hxId}')`
                msg = '谢谢!稍后我们的置业管家会亲自联系您,请耐心等候.'

            } else {
                buildSql = '1'
                msg = '操作成功.'

            }
            return { buildSql, msg }
        }

        if (id && uid) {

            //修改用户意向
            if (id && id != 0) {
                let sql = `SELECT id,sq,qy,name FROM home_base WHERE id='${pid}'`
                let result = yield this._daoModel.query(sql)
                let home = result.rows[0]

                let userSql = `SELECT user_id,user_name,user_mobile FROM crm_user WHERE user_id='${uid}'`
                let userResult = yield this._daoModel.query(userSql)
                let user = userResult.rows[0]

                //默认接入佛山接口
                let apiUrl = "http://www.fangkejia.com/jiwuyun/face/customer/access/074bcb138a9277b3"
                if (city == "佛山市") {
                    apiUrl = "http://www.fangkejia.com/jiwuyun/face/customer/access/074bcb138a9277b3"
                } else if (city == "肇庆市") {
                    apiUrl = "http://www.fangkejia.com/jiwuyun/face/customer/access/47f388851f1ea99d"
                } else {
                    apiUrl = "http://www.fangkejia.com/jiwuyun/face/customer/access/074bcb138a9277b3"
                }

                if (home) {
                    //意向城市
                    let intentionCity = home.sq
                    //意向区域
                    let intentionArea = home.qy
                    intentionArea = intentionArea.substring(0, intentionArea.length - 1)
                    //意向楼盘
                    let intentionBuild = home.name
                    //意向户型
                    let intentionType = '待定'
                    //意向面积
                    let intentionMj = '待定'

                    let updateSql = `UPDATE crm_user set city='${intentionCity}',yxqy='${intentionArea}',lp_id='${pid}',hx_id='${hxId}' where user_id='${uid}'`
                    let updateResult = yield this._daoModel.query(updateSql)

                    if (intentionCity == "佛山市") {
                        apiUrl = "http://www.fangkejia.com/jiwuyun/face/customer/access/074bcb138a9277b3"
                    } else if (intentionCity == "肇庆市") {
                        apiUrl = "http://www.fangkejia.com/jiwuyun/face/customer/access/47f388851f1ea99d"
                    } else {
                        apiUrl = "http://www.fangkejia.com/jiwuyun/face/customer/access/074bcb138a9277b3"
                    }

                    if (jjx && jjx != 0) {
                        if (jjx == '1') {
                            intentionType = '一室'
                        } else if (jjx == '2') {
                            intentionType = '二室'
                        } else if (jjx == '3') {
                            intentionType = '三室'
                        } else if (jjx == '4') {
                            intentionType = '四室'
                        } else if (jjx >= '5') {
                            intentionType = '五室及以上'
                        } else {
                            intentionType = '待定'
                        }
                        intentionMj = '0㎡-' + mj + '㎡'
                    } else {
                        intentionType = '待定'
                    }

                    var apiData = rpc.request({
                        url: apiUrl,
                        method: 'POST',
                        body: JSON.stringify({
                            "trueName": "官网用户",
                            "mobile": user.user_mobile,
                            "sex": "待定",
                            "intentionLevel": "待定",
                            "buyQualification": "待定",
                            "buyPurpose": "待定",
                            "loanQuota": "待定",
                            "age": "待定",
                            "intentionPrice": "待定",
                            "intentionbuild": intentionBuild,
                            "intentionarea": intentionArea,
                            "intentionHouse": intentionType,
                            "intentionAreaMinMax": intentionMj,
                            "renovationType": "待定"
                        }),
                        headers: {
                            'Content-Type': 'application/json'
                        }
                    }).then(function (ApiData) {
                        ApiData = ApiData.toString('uft-8');
                        ApiData = JSON.parse(ApiData)
                        console.log(ApiData)
                    });

                } else {
                    var apiData = rpc.request({
                        url: apiUrl,
                        method: 'POST',
                        body: JSON.stringify({
                            "trueName": "官网用户",
                            "mobile": user.user_mobile,
                            "sex": "待定",
                            "intentionLevel": "待定",
                            "buyQualification": "待定",
                            "buyPurpose": "待定",
                            "loanQuota": "待定",
                            "age": "待定",
                            "intentionPrice": "待定",
                            "intentionbuild": "待定",
                            "intentionarea": "待定",
                            "intentionHouse": "待定",
                            "intentionAreaMinMax": "待定",
                            "renovationType": "待定"
                        }),
                        headers: {
                            'Content-Type': 'application/json'
                        }
                    }).then(function (ApiData) {
                        ApiData = ApiData.toString('uft-8');
                        ApiData = JSON.parse(ApiData)
                        console.log(ApiData)
                    });
                }

                let resSql = dealSql(uid, pid, now, type, hxId, keepId)
                if (resSql.buildSql != '') {
                    if (resSql.buildSql != '1') {
                        let buildResult = yield this._daoModel.query(resSql.buildSql)
                        if (type == '2' || type == '3' || type == '4') {
                            msg = resSql.msg + "业务流水号:" + buildResult.rows.insertId
                        } else {
                            msg = resSql.msg
                        }
                    } else {
                        msg = resSql.msg
                    }
                }
            }

            // 插入crm_user_build 用于追踪哪个楼盘或置业管家
            // let today = date.format(new Date(), 'YYYY-MM-DD HH:mm:ss');
            // let insert_crm_user_build_sql = `INSERT INTO crm_user_build(uid,build_id,ask_time) VALUES('${uid}',${pid},'${today}')`
            // let insert_crm_user_build_result = yield this._daoModel.query(insert_crm_user_build_sql)
            // console.log("insert_crm_user_build_result.rows.insertId:" + insert_crm_user_build_result.rows.insertId)
            return { code: 1, successed: true, msg: msg }
        }
        return { code: 1, successed: true, msg: msg + "业务流水号:0000" }
    }



    //获取getwxacode
    * getwxacode(req, res) {
        let id = req.query.id;//id
        // id="90c7e2fa-9e9d-412e-a72d-1cd6e9e1e72b";
        let appID = config.wechat_mini.appID;
        let appSecret = config.wechat_mini.appSecret;
        let a = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appID + "&secret=" + appSecret;
        var apiData = yield rpc.request({
            url: a,
            method: 'POST',
            body: ""
        });
        apiData = apiData.toString('uft-8');
        apiData = JSON.parse(apiData)
        // let ok = apiData.successed ? true : false;
        let token = apiData.access_token
        // return {token:token}
        if (token) {
            //getwxacode
            let aurl = "https://api.weixin.qq.com/wxa/getwxacode?access_token=" + token;
            var apiData2 = yield rpc.request({
                // url: "https://api.weixin.qq.com/wxa/getwxacode?access_token=" + token;
                url: aurl,
                encoding: 'base64',
                json: {
                    "path": "pages/rich_text/rich_text?id=" + id
                },
                method: 'POST',
                responseType: 'arraybuffer',
                header: { "Content-Type": "Content-Type:application/json" }
            });
            // apiData2 = apiData2.toString('uft-8');
            // apiData2 = JSON.parse(apiData2)
            let ok = apiData2.successed ? true : false;
            return { code: 0, successed: ok, apiData: apiData2 }
        }
        return { code: 0, successed: false, apiData: apiData, token: token }
    }


    //获取楼盘二维码
    * getwxacodelp(req, res) {
        let id = req.query.id;//id
        // id="90c7e2fa-9e9d-412e-a72d-1cd6e9e1e72b";
        let appID = config.wechat_mini.appID;
        let appSecret = config.wechat_mini.appSecret;
        let a = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appID + "&secret=" + appSecret;
        var apiData = yield rpc.request({
            url: a,
            method: 'POST',
            body: ""
        });
        apiData = apiData.toString('uft-8');
        apiData = JSON.parse(apiData)
        // let ok = apiData.successed ? true : false;
        let token = apiData.access_token
        // return {token:token}
        if (token) {
            //getwxacode
            let aurl = "https://api.weixin.qq.com/wxa/getwxacode?access_token=" + token;
            var apiData2 = yield rpc.request({
                // url: "https://api.weixin.qq.com/wxa/getwxacode?access_token=" + token;
                url: aurl,
                encoding: 'base64',
                json: {
                    "path": "pages/goods_detailnew/goods_detailnew?id=" + id
                },
                method: 'POST',
                responseType: 'arraybuffer',
                header: { "Content-Type": "Content-Type:application/json" }
            });
            // apiData2 = apiData2.toString('uft-8');
            // apiData2 = JSON.parse(apiData2)
            let ok = apiData2.successed ? true : false;
            return { code: 0, successed: ok, apiData: apiData2 }
        }
        return { code: 0, successed: false, apiData: apiData, token: token }
    }



    //web端订阅状态跟预约看房
    * getDingYve(req, res) {
        let pid = req.body.pid;//楼盘id
        let uid = req.body.uid;//用户id
        let phoneNumber = req.body.phoneNumber;//手机号
        let ydDatetime = req.body.ydDatetime;//预定时间 
        let msg = '谢谢!稍后我们的置业管家会亲自联系您,请耐心等候.';
        let sql = `select user_id,user_mobile from crm_user where user_id='${uid}'`
        let result = yield this._daoModel.query(sql);
        let user = result.rows[0]
        if (user) {
            //修改用户意向
            if (pid && pid != 0) {
                let sql = `SELECT id,sq,qy FROM home_base WHERE id='${pid}'`
                let result = yield this._daoModel.query(sql)
                let home = result.rows[0]
                if (home) {
                    let sq = home.sq
                    let qy = home.qy
                    let updateSql = `UPDATE crm_user set city='${sq}',yxqy='${qy}',lp_id='${pid}' where user_id='${uid}'`
                    let updateResult = yield this._daoModel.query(updateSql)
                }
            }

            // 插入crm_user_build 用于追踪哪个楼盘或置业管家
            let today = date.format(new Date(), 'YYYY-MM-DD HH:mm:ss');
            let insert_crm_user_build_sql2 = `INSERT INTO crm_user_build(uid,build_id,ask_time) VALUES('${uid}',${pid},'${today}')`
            let insert_crm_user_build_result2 = yield this._daoModel.query(insert_crm_user_build_sql2);

            //修改手机号
            if (user.user_mobile != phoneNumber) {
                let update_crm_user_sql = `UPDATE crm_user set user_mobile='${phoneNumber}' where user_id='${uid}'`
                let update_crm_user_result = yield this._daoModel.query(update_crm_user_sql);
                return { code: 1, successed: true, uphone: phoneNumber, msg: msg + "业务流水号:" + insert_crm_user_build_result2.rows.insertId }
            } else {
                return { code: 1, successed: false, msg: "已通知置业管家," + msg }
            }

        }
        return { code: 1, successed: true, skey: skey, iv: iv, uphone: phoneNumber, msg: msg + "业务流水号:0000" }
    }



    //帮我找房,预约看房（注册并发送数据至房客家）
    * getFindHome(req, res) {
        let pid = req.body.pid || 0;//楼盘id
        let city = req.body.city || '';//意向城市
        let mobile = req.body.mobile;//手机号
        let intentionPrice = req.body.intentionPrice;//总价预算,只能填入：XX万-XX万的数字，如50万-100万，或填入待定，如填入错误默认为空
        let intentionarea = req.body.intentionarea;//意向区域
        let intentionHouse = req.body.intentionHouse;//意向户型,只能填入：不限、一室、二室、三室、四室、五室及以上、待定，如填入错误默认为空
        let intentionAreaMinMax = req.body.intentionAreaMinMax;//面积,只能填入：XX㎡-XX㎡的数字，如80㎡-100㎡，或填入待定，如填入错误默认为空
        let msg = '谢谢!稍后我们的置业管家会亲自联系您,请耐心等候.';
        if (mobile) {
            let sql = `select user_id,user_mobile,user_name,user_image from crm_user where user_mobile='${mobile}';`
            let result = yield this._daoModel.query(sql)
            let userInfo = result.rows[0]
            let today = date.format(new Date(), 'YYYY-MM-DD HH:mm:ss'); //实时时间
            if (userInfo) {
                let user_id = userInfo.user_id
                if (user_id) {
                    let sql_update = `UPDATE crm_user SET khzxsj='${today}',lp_id='${pid}' WHERE user_mobile='${mobile}'`
                    if (intentionarea) {
                        sql_update = `UPDATE crm_user SET khzxsj='${today}',yxqy='${intentionarea}',lp_id='${pid}' WHERE user_mobile='${mobile}'`
                    }
                    let result_update = yield this._daoModel.query(sql_update)
                }
            } else {
                let user_name = "用户_" + mobile
                let user_id = UUID.v1();
                let user_sex = '1';
                let user_serial = 0;
                let khly = '1';//0微信小程序 1 pc 2 移动
                let result_fun_GetSerial = yield this._daoModel.query('select fun_GetSerial()')
                user_serial = result_fun_GetSerial.rows[0]['fun_GetSerial()']
                // console.log('...................................',user_serial)
                let inser_crm_user = `INSERT INTO crm_user(user_image,user_id,user_name,user_sex,user_create_date,user_serial,user_mobile,khly,khscsj,khzxsj,ydscsj,lp_id) VALUES('http://image.xinghe00.com/user_image.jpg','${user_id}','${user_name}','${user_sex}','${today}','${user_serial}','${mobile}','${khly}','${today}','${today}','${today}','${pid}');`;
                if (intentionarea) {
                    inser_crm_user = `INSERT INTO crm_user(user_image,user_id,user_name,user_sex,user_create_date,user_serial,user_mobile,khly,khscsj,khzxsj,ydscsj,yxqy,lp_id) VALUES('http://image.xinghe00.com/user_image.jpg','${user_id}','${user_name}','${user_sex}','${today}','${user_serial}','${mobile}','${khly}','${today}','${today}','${today}','${intentionarea}','${pid}');`
                }
                let result_inser_crm_user = yield this._daoModel.query(inser_crm_user)
            }
            //默认接入佛山接口
            let apiUrl = "http://www.fangkejia.com/jiwuyun/face/customer/access/074bcb138a9277b3"
            if (city == "佛山市") {
                apiUrl = "http://www.fangkejia.com/jiwuyun/face/customer/access/074bcb138a9277b3"
            } else if (city == "肇庆市") {
                apiUrl = "http://www.fangkejia.com/jiwuyun/face/customer/access/47f388851f1ea99d"
            } else {
                apiUrl = "http://www.fangkejia.com/jiwuyun/face/customer/access/074bcb138a9277b3"
            }
            if (intentionPrice) {
                // intentionPrice = `0万-${intentionPrice}万`
            } else {
                intentionPrice = `待定`
            }
            if (intentionarea) {
                if (intentionarea == '不限') {
                    intentionarea = '待定'
                } else {
                    intentionarea = intentionarea.substring(0, intentionarea.length - 1)
                }
            } else {
                intentionarea = '待定'
            }
            if (intentionHouse) {

            } else {
                intentionHouse = '待定'
            }
            if (intentionAreaMinMax) {
                // intentionAreaMinMax=`0㎡-${intentionAreaMinMax}㎡`
            } else {
                intentionAreaMinMax = `待定`
            }
            let intentionbuild = '';
            if (pid && pid != 0) {
                let sql_homebase = `SELECT name FROM home_base WHERE id='${pid}';`
                let result_homebase = yield this._daoModel.query(sql_homebase)
                let homeBaseInfo = result_homebase.rows[0]
                if (homeBaseInfo) {
                    intentionbuild = homeBaseInfo.name;
                }
            }
            let sql_crm_findroom = `INSERT INTO crm_findroom (mobile, intentionPrice, intentionbuild, intentionarea, intentionHouse, intentionAreaMinMax, create_date, intentioncity) VALUES ('${mobile}', '${intentionPrice}', '${intentionbuild}', '${intentionarea}', '${intentionHouse}', '${intentionAreaMinMax}', '${today}', '${city}');`;
            let result_crm_findroom = yield this._daoModel.query(sql_crm_findroom)
            var apiData = yield rpc.request({
                url: apiUrl,
                method: 'POST',
                body: JSON.stringify({
                    "trueName": "官网用户",
                    "mobile": mobile,
                    "sex": "待定",
                    "intentionLevel": "待定",
                    "buyQualification": "待定",
                    "buyPurpose": "待定",
                    "loanQuota": "待定",
                    "age": "待定",
                    "intentionPrice": intentionPrice,
                    "intentionbuild": intentionbuild,
                    "intentionarea": intentionarea,
                    "intentionHouse": intentionHouse,
                    "intentionAreaMinMax": intentionAreaMinMax,
                    "renovationType": "待定"
                }),
                headers: {
                    'Content-Type': 'application/json'
                }
            }).then(function (ApiData) {
                ApiData = ApiData.toString('uft-8');
                ApiData = JSON.parse(ApiData)
                console.log(ApiData)
            });

            return { code: 1, successed: true, msg: msg }
        } else {
            return { code: 0, successed: false, msg: "请填写手机号！" }
        }


    }

};

exports = module.exports = LoginController;